package cn.sample.security.json.handler;

import cn.sample.common.result.JsonResult;
import cn.sample.common.result.ResultCode;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <h2></h2>
 *
 * <p>Json 未经身份验证的异常处理</p>
 *
 * @author HKD
 */
@Component
public class JsonUnAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 响应状态
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //返回Json格式
        response.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(JsonResult.result(ResultCode.SC_UNAUTHORIZED,null)));
        writer.flush();
        writer.close();
    }
}
